package main

import (
	"golang.org/x/net/context"
	"fmt"
	"net"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc"
	pb "../../proto/hello"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/metadata"
)

const (
	Address = "127.0.0.1:50052"
)

type helloService struct {
}

var HelloService = helloService{}

func (h helloService) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloResponse, error) {

	resp := new(pb.HelloResponse)
	resp.Message = fmt.Sprintf("hello %s.", in.Name)

	return resp, nil
}

func main() {

	listen, err := net.Listen("tcp", Address)
	if err != nil {
		grpclog.Fatalf("failed to listen : %v", err)
	}

	creds, err := credentials.NewServerTLSFromFile("src/grpc/demo/keys/server.pem", "src/grpc/demo/keys/server.key")

	if err != nil {
		grpclog.Fatalf("Failed to generate credentials %v", err)
	}

	var opts []grpc.ServerOption

	opts = append(opts, grpc.Creds(creds))
	//注册interceptor
	opts = append(opts, grpc.UnaryInterceptor(interceptor))

	// 实例化grpc Server, 并开启TLS认证
	s := grpc.NewServer(opts...)

	//s := grpc.NewServer()
	fmt.Println("start")
	pb.RegisterHelloServer(s, HelloService)
	fmt.Println("listen on " + Address)
	s.Serve(listen)

}

func auth(ctx context.Context) error {
	metadata.FromIncomingContext(ctx)
	return nil
}

// interceptor 拦截器
func interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	err := auth(ctx)
	if err != nil {
		return nil, err
	}
	// 继续处理请求
	return handler(ctx, req)
}
